<template>
  <!-- 6第一、三人称漫游/2W键控制角色模型运动 -->
  <div @keydown="handleKeyDown" @keyup="handleKeyUp" tabindex="0">
    <div id="webgl" class="main"></div>
  </div>
</template>
<script setup>
// import TWEEN from "@tweenjs/tween.js";
import * as THREE from "three";
import { onMounted } from "vue";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
// 引入CSS2渲染器CSS2DRenderer和CSS2模型对象CSS2DObject
import Mesh from "./mesh.js";
import camera from "./camera.js";
// 创建一个3D场景scene
const scene = new THREE.Scene();
const { model, player, mixer } = Mesh;
scene.add(model);
// AxesHelper：辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
scene.add(axesHelper);
//光源设置
const ambient = new THREE.AmbientLight(0xffffff, 1);
scene.add(ambient);
// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
// 设置光源的方向：通过光源position属性和目标指向对象的position属性计算
directionalLight.position.set(80, 100, 50);
scene.add(directionalLight);
var width = window.innerWidth;
var height = window.innerHeight;
// 将相机添加到场景
scene.add(camera);
// 创建渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, //添加抗锯齿
  preserveDrawingBuffer: true,
});
renderer.setSize(width, height);
renderer.outputEncoding = THREE.sRGBEncoding;

// 设置相机控件轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
console.log("", controls);
const keySatates = {
  W: false,
  S: false,
  A: false,
  D: false,
};
const handleKeyDown = (event) => {
  if (event.code == "KeyW") keySatates.W = true;
  if (event.code == "KeyS") keySatates.S = true;
  if (event.code == "KeyA") keySatates.A = true;
  if (event.code == "KeyD") keySatates.D = true;
  console.log(player);
  console.log("", mixer);
  mixer.timeScale = 1;
};
const handleKeyUp = (event) => {
  if (event.code == "KeyW") keySatates.W = false;
  if (event.code == "KeyS") keySatates.S = false;
  if (event.code == "KeyA") keySatates.A = false;
  if (event.code == "KeyD") keySatates.D = false;
  mixer.timeScale = 0;
};
const v = new THREE.Vector3(0, 0, -3); //z轴速度
const v2 = new THREE.Vector3(0, 0, 3); //z轴速度
const clock = new THREE.Clock();
const render = () => {
  renderer.render(scene, camera);
  //clock.getDelta()方法获得loop()两次执行时间间隔
  const frameT = clock.getDelta();
  const timeX1 = v.clone().multiplyScalar(frameT);
  const timeX2 = v2.clone().multiplyScalar(frameT);
  if (keySatates.W) {
    player.position.add(timeX1);
  }
  if (keySatates.S) {
    player.position.add(timeX2);
  }
  // 浏览器用于定时循环操作某一个函数，一秒钟60次左右
  window.requestAnimationFrame(render);
};

render();
window.onresize = function () {
  width = window.innerWidth;
  height = window.innerHeight;
  renderer.setSize(width, height);
};
onMounted(() => {
  document.getElementById("webgl").appendChild(renderer.domElement);
});
</script>
<style scoped>
</style>